package eleTrain.StatDB;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class TrainedHandsStatDatabase {

	Connection conn;

	String generationName;

	PreparedStatement existsCountForHandNoStmt;
	PreparedStatement insertCountForHandNoStmt;
	PreparedStatement incrementCountForHandNoStmt;

	public TrainedHandsStatDatabase(String generationName) {
		System.out.println(this.getClass() + "::generationName:"
				+ generationName);
		this.generationName = generationName;
		try {
			// Class.forName("org.postggresql.Driver");
			conn = DriverManager.getConnection(
					"jdbc:postgresql://localhost/TrainedHandsStat", "postgres",
					"breakdance85");
			existsCountForHandNoStmt = conn
					.prepareStatement("SELECT times_trained FROM trained_hands WHERE generation_name = ? AND hand_no = ?");
			insertCountForHandNoStmt = conn
					.prepareStatement("INSERT INTO trained_hands (generation_name, hand_no, times_trained) VALUES (?, ?, ?)");
			incrementCountForHandNoStmt = conn
					.prepareStatement("UPDATE trained_hands SET times_trained = times_trained + 1 WHERE generation_name = ? AND hand_no = ?");

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void countHandTrained(long handNo) {
		if (!existCountForHandNo(handNo)) {
			insertCountForHandNo(handNo);
		} else {
			incrementCountForHandNo(handNo);
		}
	}

	synchronized void incrementCountForHandNo(long handNo) {
		try {
			incrementCountForHandNoStmt.setString(1, generationName);
			incrementCountForHandNoStmt.setLong(2, handNo);
			incrementCountForHandNoStmt.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	synchronized void insertCountForHandNo(long handNo) {
		try {
			insertCountForHandNoStmt.setString(1, generationName);
			insertCountForHandNoStmt.setLong(2, handNo);
			insertCountForHandNoStmt.setInt(3, 1);
			insertCountForHandNoStmt.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	boolean existCountForHandNo(long handNo) {
		try {
			existsCountForHandNoStmt.setString(1, generationName);
			existsCountForHandNoStmt.setLong(2, handNo);
			ResultSet rs = existsCountForHandNoStmt.executeQuery();
			return rs.next();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

}
